package com.raos.example.swagger.service;

import com.raos.example.swagger.model.SysUser;
import com.raos.example.swagger.response.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * UserService
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2022/6/21 20:46
 */
@Slf4j
@Service
public class UserService {

    private List<SysUser> list = new ArrayList<>();

    public List<SysUser> queryAll() {
        return list;
    }

    public int save(SysUser sysUser) {
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RRException("新增时用户对象不能为空");
        }
        list.forEach(sysUser1 -> {
            if (sysUser.getUserId().equals(sysUser1.getUserId())) {
                throw new RRException("对象ID已经存在!");
            }
        });
        list.add(sysUser);
        log.info("添加结果=[{}]", list.size());
        return 1;
    }

    public int delete(Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            throw new RRException("");
        }
        int num = 0;
        Iterator<SysUser> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getUserId().equals(userId)) {
                iterator.remove();
                num = 1;
                break;
            }
        }
        String msg = num > 0 ? "未找到用户对象" : "用户对象存在开始删除";
        log.info(msg);
        return num;
    }

}
